﻿using Shopfloormanagement.CustomControls;
using LSQL;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace Shopfloormanagement.Forms
{
    public partial class Form_Layout : Form
    {
        public static Form_Layout instance = new Form_Layout();
        public static Form_Layout frm = new Form_Layout()
            ;
        private bool dragging = false;
        private Point dragCursorPoint;
        private Point dragFormPoint;
        int ControlCount = 1;
        int interval = 10;
        int TotalHeight = 0;
        Point P1;
        Point P2;
        Point P3;
        Point P4;
        string Type1 = "";
        Control control1 = null;
        Control control2 = null;
        Control EditControl1 = null;
        public Form_Layout()
        {
            instance = this;
            frm = this;
            InitializeComponent();
            txtID1.Text = "";
            //btn01
            btn01.MouseDown += Control_MouseDown;
            btn01.MouseMove += Control_MouseMove;
            btn01.MouseUp += Control_MouseUp;
            P1 = btn01.Location;
            //btn02
            btn02.MouseDown += Control_MouseDown;
            btn02.MouseMove += Control_MouseMove;
            btn02.MouseUp += Control_MouseUp;
            P2 = btn02.Location;
            //btn03
            btn03.MouseDown += Control_MouseDown;
            btn03.MouseMove += Control_MouseMove;
            btn03.MouseUp += Control_MouseUp;
            P3 = btn03.Location;
            LoadFactory();
        }
        private void LoadFactory()
        {
            DataTable dt1 = SQL.ReturnDataTable3(SystemInfo.sys, "Factories", "Del_tag=0");
            cmbFactory1.DisplayMember = "FactoryName";
            cmbFactory1.ValueMember = "ID";
            cmbFactory1.DataSource = dt1;
            cmbFactory1.SelectedIndex = -1;
        }
        private void cmbFactory1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int a = Convert.ToInt32(cmbFactory1.SelectedValue);
            DataTable dt2 = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", "isDisplay =1 and Del_tag=0");
            cmbDepartment1.DisplayMember = "DepartmentName";
            cmbDepartment1.ValueMember = "ID";
            cmbDepartment1.DataSource = dt2;
        }
        private void Form_Layout_SizeChanged(object sender, EventArgs e)
        {
            panel1.Height = this.Height - 93;
            uiLine5.Height = this.Height - 76;
            uiLine6.Height = this.Height - 76;
        }
        private void btnS_Click(object sender, EventArgs e)
        {
            Type1 = "S";
        }
        private void btnQ_Click(object sender, EventArgs e)
        {
            Type1 = "Q";
        }
        private void btnD_Click(object sender, EventArgs e)
        {
            Type1 = "D";
        }
        private void btnC_Click(object sender, EventArgs e)
        {
            Type1 = "C";
        }
        private void btnLoadLayout1_Click(object sender, EventArgs e)
        {
            LoadLayout();
        }

        private int departmengID;
        private void LoadLayout()
        {
            panel1.Controls.Clear();
            TotalHeight = 0;
            int FactoryID = Convert.ToInt32(cmbFactory1.SelectedValue);
            int DepartmentID = Convert.ToInt32(cmbDepartment1.SelectedValue);

            if (publicFunc.GetUserScope(SystemInfo.userID,DepartmentID) == false)
            {
                XtraMessageBox.Show( "You have no permission");
                return;
            }
            string Condition = "FactoryID=" + FactoryID + " and DepartmentID=" + DepartmentID + " and Del_tag=0";
            DataTable dt1 = SQL.ReturnDataTable3(SystemInfo.SQL, "Interface", Condition);
            string BeforeName = "";
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                if (BeforeName != "折线图")
                {
                    if (dt1.Rows[i][6].ToString() == "红绿表格")
                    {
                        ControlCount = Convert.ToInt32(dt1.Rows[i][3].ToString());
                        string ControlName1 = dt1.Rows[i][5].ToString() + "#" + dt1.Rows[i][6].ToString() + "#" + dt1.Rows[i][4].ToString() + "#" + dt1.Rows[i][7].ToString() + "#" + dt1.Rows[i][8].ToString() + "#" + dt1.Rows[i][9].ToString() + "#" + dt1.Rows[i][10].ToString() + "#" + dt1.Rows[i][11].ToString() + "#" + dt1.Rows[i][12].ToString() + "#" + dt1.Rows[i][13].ToString();
                        //判断i是不是比控件总数-1小，在判断下一个控件是不是文本表格
                        if (i < dt1.Rows.Count - 1)
                        {
                            if (dt1.Rows[i + 1][6].ToString() == "文本表格")
                            {
                                string ControlName2 = dt1.Rows[i + 1][5].ToString() + "#" + dt1.Rows[i + 1][6].ToString() + "#" + dt1.Rows[i + 1][4].ToString() + "#" + dt1.Rows[i + 1][7].ToString() + "#" + dt1.Rows[i + 1][8].ToString() + "#" + dt1.Rows[i + 1][9].ToString() + "#" + dt1.Rows[i + 1][10].ToString() + "#" + dt1.Rows[i + 1][11].ToString() + "#" + dt1.Rows[i + 1][12].ToString() + "#" + dt1.Rows[i + 1][13].ToString();
                                AddRGtable2(ControlName1, ControlName2);
                            }
                            else
                            {
                                AddRGtable(ControlName1, panel1);
                            }
                        }
                        else
                        {
                            AddRGtable(ControlName1, panel1);
                        }
                        BeforeName = dt1.Rows[i][6].ToString();
                    }
                    else if (dt1.Rows[i][6].ToString() == "文字表格")
                    {
                        ControlCount = Convert.ToInt32(dt1.Rows[i][3].ToString());
                        string ControlName = dt1.Rows[i][5].ToString() + "#" + dt1.Rows[i][6].ToString() + "#" + dt1.Rows[i][4].ToString() + "#" + dt1.Rows[i][7].ToString() + "#" + dt1.Rows[i][8].ToString() + "#" + dt1.Rows[i][9].ToString() + "#" + dt1.Rows[i][10].ToString() + "#" + dt1.Rows[i][11].ToString() + "#" + dt1.Rows[i][12].ToString() + "#" + dt1.Rows[i][13].ToString();
                        AddCharactertable(ControlName, panel1);
                        BeforeName = dt1.Rows[i][6].ToString();
                    }
                    else if (dt1.Rows[i][6].ToString() == "折线图")
                    {
                        ControlCount = Convert.ToInt32(dt1.Rows[i][3].ToString());
                        string ControlName1 = dt1.Rows[i][5].ToString() + "#" + dt1.Rows[i][6].ToString() + "#" + dt1.Rows[i][4].ToString() + "#" + dt1.Rows[i][7].ToString() + "#" + dt1.Rows[i][8].ToString() + "#" + dt1.Rows[i][9].ToString() + "#" + dt1.Rows[i][10].ToString() + "#" + dt1.Rows[i][11].ToString() + "#" + dt1.Rows[i][12].ToString() + "#" + dt1.Rows[i][13].ToString();
                        string ControlName2 = dt1.Rows[i + 1][5].ToString() + "#" + dt1.Rows[i + 1][6].ToString() + "#" + dt1.Rows[i + 1][4].ToString() + "#" + dt1.Rows[i + 1][7].ToString() + "#" + dt1.Rows[i + 1][8].ToString() + "#" + dt1.Rows[i + 1][9].ToString() + "#" + dt1.Rows[i + 1][10].ToString() + "#" + dt1.Rows[i + 1][11].ToString() + "#" + dt1.Rows[i + 1][12].ToString() + "#" + dt1.Rows[i + 1][13].ToString();
                        AddLineChart(ControlName1, ControlName2);
                        BeforeName = dt1.Rows[i][6].ToString();
                    }
                }
                else
                {
                    BeforeName = "";
                }
            }
        }
        //鼠标拖放事件
        private void Control_MouseDown(object sender, MouseEventArgs e)
        {
            if (Type1 != "")
            {
                Control clickedControl = sender as Control;
                if (clickedControl != null)
                {
                    if (e.Button == MouseButtons.Left)
                    {
                        dragging = true;
                        dragCursorPoint = Cursor.Position;
                        dragFormPoint = clickedControl.Location;
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择一种类型！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Control_MouseMove(object sender, MouseEventArgs e)
        {
            Control clickedControl = sender as Control;
            if (clickedControl != null)
            {
                if (dragging)
                {
                    Point dif = Point.Subtract(Cursor.Position, new Size(dragCursorPoint));
                    clickedControl.Location = Point.Add(dragFormPoint, new Size(dif));
                }
            }
        }
        private void Control_MouseUp(object sender, MouseEventArgs e)
        {
            Control clickedControl = sender as Control;
            Form_LayoutParameters frm = null;
            if (clickedControl != null)
            {
                dragging = false;
                if (clickedControl.Location.X >= panel1.Location.X && clickedControl.Location.Y >= panel1.Location.Y)
                {
                    if (clickedControl.Location.X <= panel1.Location.X + panel1.Width && clickedControl.Location.Y <= panel1.Location.Y + panel1.Height)
                    {
                        frm = new Form_LayoutParameters();
                        frm.FormType = clickedControl.Text;
                        frm.txtType1.Text = Type1;
                        frm.cmbName1.Text = clickedControl.Text;
                    }
                }
            }
            if (clickedControl.Name == "btn01")
            {
                clickedControl.Location = P1;
            }
            if (clickedControl.Name == "btn02")
            {
                clickedControl.Location = P2;
            }
            if (clickedControl.Name == "btn03")
            {
                clickedControl.Location = P3;
            }
            if (frm != null)
            {
                frm.ShowDialog();
            }
        }
        //添加四种控件      
        //public void AddRGtable(string ControlName, Control ParentControl)
        public void AddRGtable(string ControlName, Control ParentControl)
        {
            Label label1 = new Label();
            Label label2 = new Label();
            Label label3 = new Label();
            string[] c = ControlName.Split(new char[] { '#' });
            label1.Name = ControlName;
            label2.Name = ControlName;
            label3.Name = ControlName;
            label1.Text = "Indicator: " + c[8];
            label2.Text = c[2];
            label3.Text = "Target/Limit: " + c[9];
            label1.AutoSize = false;
            label2.AutoSize = false;
            label3.AutoSize = false;
            label1.TextAlign = ContentAlignment.MiddleLeft;
            label2.TextAlign = ContentAlignment.MiddleCenter;
            label3.TextAlign = ContentAlignment.MiddleRight;
            label1.Width = 300;
            label2.Width = 300;
            label3.Width = 300;
            label1.Location = new Point(3, 3);
            label2.Location = new Point(350, 3);
            label3.Location = new Point(697, 3);
            label1.BackColor = Color.Transparent;
            label2.BackColor = Color.Transparent;
            label3.BackColor = Color.Transparent;

            UIPanel panel = new UIPanel();
            panel.Controls.Add(label1);
            panel.Controls.Add(label2);
            panel.Controls.Add(label3);
            panel.Text = ControlCount + "#" + ControlName;
            panel.Name = ControlCount + "#" + ControlName;
            panel.Font = new Font("宋体", 9);
            panel.Size = new Size(1000, 105);
            if (ParentControl == panel1)
            {
                panel1.AutoScrollPosition = new Point(0, 0);
                panel.Location = new Point(30, interval + TotalHeight);
                TotalHeight = panel.Height + panel.Top;
                panel.Enter += uiPanel_Enter;
                panel.Leave += uiPanel_Leave;
            }
            else
            {
                panel.Location = new Point(0, ParentControl.Height - panel.Height);
            }

            panel.Parent = ParentControl;
            panel.BringToFront();
            panel.ContextMenuStrip = contextMenuStrip1;

            DataGridView dgv = new DataGridView();
            dgv.Name = "dgv_" + ControlCount.ToString();
            dgv.Parent = panel;
            dgv.Location = new Point(3, 30);
            dgv.Size = new Size(panel.Width - 6, panel.Height - 36);
            dgv.RowHeadersVisible = false;
            dgv.BackgroundColor = Color.White;
            dgv.BorderStyle = BorderStyle.None;
            dgv.AllowUserToAddRows = false;
            dgv.AllowUserToDeleteRows = false;
            dgv.DefaultCellStyle.Font = new Font("Arial", 6);
            dgv.ReadOnly = true;
            for (int i = 0; i < 32; i++)
            {
                DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
                if (i == 0)
                {
                    column2.HeaderText = "Day";
                }
                else
                {
                    column2.HeaderText = i.ToString();
                }
                column2.Width = dgv.Width / 32;
                dgv.Columns.Add(column2);
            }
            string[] b = ControlName.Split(new char[] { '#' });
            dgv.Rows.Add(b[4]);
            panel.Controls.Add(dgv);
            ParentControl.Controls.Add(panel);
            ControlCount++;
        }
        public void AddRGtable2(string ControlName1, string ControlName2)
        {
            panel1.AutoScrollPosition = new Point(0, 0);
            Label label1 = new Label();
            Label label2 = new Label();
            Label label3 = new Label();
            string[] c = ControlName1.Split(new char[] { '#' });
            label1.Name = ControlName1;
            label2.Name = ControlName1;
            label3.Name = ControlName1;
            label1.Text = "Indicator: " + c[8];
            label2.Text = c[2];
            label3.Text = "Target/Limit: " + c[9];
            label1.AutoSize = false;
            label2.AutoSize = false;
            label3.AutoSize = false;
            label1.TextAlign = ContentAlignment.MiddleLeft;
            label2.TextAlign = ContentAlignment.MiddleCenter;
            label3.TextAlign = ContentAlignment.MiddleRight;
            label1.Width = 300;
            label2.Width = 300;
            label3.Width = 300;
            label1.Location = new Point(3, 3);
            label2.Location = new Point(350, 3);
            label3.Location = new Point(697, 3);
            label1.BackColor = Color.Transparent;
            label2.BackColor = Color.Transparent;
            label3.BackColor = Color.Transparent;

            UIPanel panel = new UIPanel();
            panel.Controls.Add(label1);
            panel.Controls.Add(label2);
            panel.Controls.Add(label3);
            //panel.Text = ControlCount + "#" + ControlName1;
            panel.Name = ControlCount + "#" + ControlName1;
            panel.Font = new Font("宋体", 9);
            panel.Size = new Size(1000, 205);

            panel.Location = new Point(30, interval + TotalHeight);

            panel.Enter += uiPanel_Enter;
            panel.Leave += uiPanel_Leave;

            panel.Parent = panel1;
            panel.BringToFront();
            panel.ContextMenuStrip = contextMenuStrip1;

            DataGridView dgv = new DataGridView();
            dgv.Name = "dgv_" + ControlCount.ToString();
            dgv.Parent = panel;
            dgv.Location = new Point(3, 30);
            dgv.Size = new Size(panel.Width - 6, panel.Height - 150);
            dgv.RowHeadersVisible = false;
            dgv.BackgroundColor = Color.White;
            dgv.BorderStyle = BorderStyle.None;
            dgv.AllowUserToAddRows = false;
            dgv.AllowUserToDeleteRows = false;
            dgv.DefaultCellStyle.Font = new Font("Arial", 6);
            dgv.ReadOnly = true;
            for (int i = 0; i < 32; i++)
            {
                DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
                if (i == 0)
                {
                    column2.HeaderText = "Day";
                }
                else
                {
                    column2.HeaderText = i.ToString();
                }
                column2.Width = dgv.Width / 32;
                dgv.Columns.Add(column2);
            }
            string[] b = ControlName1.Split(new char[] { '#' });
            dgv.Rows.Add(b[4]);
            panel.Controls.Add(dgv);
            panel1.Controls.Add(panel);
            ControlCount++;
            TotalHeight = panel.Height + panel.Top;
            AddTexttable2(ControlName2, panel);
        }
        public void AddCharactertable(string ControlName, Control ParentControl)
        {
            Label label1 = new Label();
            Label label2 = new Label();
            Label label3 = new Label();
            string[] c = ControlName.Split(new char[] { '#' });
            label1.Text = "Indicator: " + c[8];
            label2.Text = c[2];
            label3.Text = "Target/Limit: " + c[9];
            label1.AutoSize = false;
            label2.AutoSize = false;
            label3.AutoSize = false;
            label1.TextAlign = ContentAlignment.MiddleLeft;
            label2.TextAlign = ContentAlignment.MiddleCenter;
            label3.TextAlign = ContentAlignment.MiddleRight;
            label1.Width = 300;
            label2.Width = 300;
            label3.Width = 300;
            label1.Location = new Point(3, 3);
            label2.Location = new Point(350, 3);
            label3.Location = new Point(697, 3);
            label1.BackColor = Color.Transparent;
            label2.BackColor = Color.Transparent;
            label3.BackColor = Color.Transparent;

            UIPanel panel = new UIPanel();
            panel.Controls.Add(label1);
            panel.Controls.Add(label2);
            panel.Controls.Add(label3);
            panel.Text = ControlCount + "#" + ControlName;
            panel.Name = ControlCount + "#" + ControlName;
            panel.Font = new Font("宋体", 9);
            panel.Size = new Size(1000, 105);
            if (ParentControl == panel1)
            {
                panel1.AutoScrollPosition = new Point(0, 0);
                panel.Location = new Point(30, interval + TotalHeight);
                TotalHeight = panel.Height + panel.Top;
                panel.Enter += uiPanel_Enter;
                panel.Leave += uiPanel_Leave;
            }
            else
            {
                panel.Location = new Point(0, ParentControl.Height - panel.Height);
            }
            panel.Parent = ParentControl;
            panel.BringToFront();
            panel.ContextMenuStrip = contextMenuStrip1;

            DataGridView dgv = new DataGridView();
            dgv.Name = "dgv_" + ControlCount.ToString();
            dgv.Parent = panel;
            dgv.Location = new Point(3, 30);
            dgv.Size = new Size(panel.Width - 6, panel.Height - 36);
            dgv.RowHeadersVisible = false;
            dgv.BackgroundColor = Color.White;
            dgv.BorderStyle = BorderStyle.None;
            dgv.AllowUserToAddRows = false;
            dgv.AllowUserToDeleteRows = false;
            dgv.DefaultCellStyle.Font = new Font("Arial", 6);
            dgv.ReadOnly = true;
            for (int i = 0; i < 32; i++)
            {
                DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
                if (i == 0)
                {
                    column2.HeaderText = "Day";
                }
                else
                {
                    column2.HeaderText = i.ToString();
                }
                column2.Width = dgv.Width / 32;
                dgv.Columns.Add(column2);
            }
            panel.Controls.Add(dgv);
            ParentControl.Controls.Add(panel);
            ControlCount++;
            string[] b = ControlName.Split(new char[] { '#' });
            if (b[3] == "1")
            {
                dgv.Rows.Add(b[4]);
            }
            else if (b[3] == "2")
            {
                dgv.Rows.Add(b[4]);
                dgv.Rows.Add(b[5]);
            }
        }
        public void AddLineChart(string ControlName1, string ControlName2)
        {
            panel1.AutoScrollPosition = new Point(0, 0);
            string[] b = ControlName2.Split(new char[] { '#' });
            UIPanel panel = new UIPanel();
            panel.Text = ControlCount + "#" + ControlName1;
            panel.Name = ControlCount + "#" + ControlName1;
            panel.Font = new Font("宋体", 9);
            panel.Location = new Point(30, interval + TotalHeight);
            //panel.Size = new Size(1000, 350);
            if (b[1] == "文本表格")
            {
                panel.Size = new Size(1000, 370);
            }
            else
            {
                panel.Size = new Size(1000, 350);
            }
            panel.Parent = panel1;
            panel.BringToFront();
            panel.Enter += uiPanel_Enter;
            panel.Leave += uiPanel_Leave;
            panel.ContextMenuStrip = contextMenuStrip1;

            LineChart2 lineChart = new LineChart2();
            string[] c = ControlName1.Split(new char[] { '#' });
            lineChart.ChartLabel1 = "Indicator: " + c[8];
            lineChart.ChartLabel2 = c[2];
            lineChart.ChartLabel3 = "Target/Limit: " + c[9];
            lineChart.Parent = panel1;
            lineChart.Name = "Line_" + ControlName1;
            lineChart.Location = new Point(3, 3);
            lineChart.Size = new Size(panel.Width - 6, panel.Height - 110);
            lineChart.XValues = new List<double>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
            lineChart.YValues = new List<double>() { 0, 1, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            panel.Controls.Add(lineChart);
            panel1.Controls.Add(panel);
            ControlCount++;
            TotalHeight = panel.Height + panel.Top;

            if (b[1] == "红绿表格")
            {
                AddRGtable(ControlName2, panel);
            }
            else if (b[1] == "文字表格")
            {
                AddCharactertable(ControlName2, panel);
            }
            else if (b[1] == "文本表格")
            {
                AddTexttable(ControlName2, panel);
            }
        }
        public void AddTexttable(string ControlName, Control ParentControl)
        {
            panel1.AutoScrollPosition = new Point(0, 0);
            UIPanel panel = new UIPanel();
            panel.Text = ControlCount + "#" + ControlName;
            panel.Name = ControlCount + "#" + ControlName;
            panel.Font = new Font("宋体", 9);
            //panel.Location = new Point(30, interval + TotalHeight);
            panel.Location = new Point(0, 270);
            panel.Size = new Size(1000, 100);
            panel.Parent = ParentControl;
            panel.BringToFront();
            panel.Enter += uiPanel_Enter;
            panel.Leave += uiPanel_Leave;
            panel.ContextMenuStrip = contextMenuStrip1;

            DataGridView dgv = new DataGridView();
            dgv.Name = "dgv_" + ControlCount.ToString();
            dgv.Parent = panel;
            dgv.Location = new Point(3, 3);
            dgv.Size = new Size(panel.Width - 6, panel.Height - 6);
            dgv.RowHeadersVisible = false;
            dgv.BackgroundColor = Color.White;
            dgv.BorderStyle = BorderStyle.None;
            dgv.AllowUserToAddRows = false;
            dgv.AllowUserToDeleteRows = false;
            dgv.ReadOnly = true;
            dgv.ColumnHeadersVisible = false;
            dgv.RowTemplate.Height = 30;
            ParentControl.Controls.Add(dgv);
            DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn();
            DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
            DataGridViewTextBoxColumn column3 = new DataGridViewTextBoxColumn();
            column1.Width = dgv.Width / 3 - 1;
            column2.Width = dgv.Width / 3 - 1;
            column3.Width = dgv.Width / 3 - 1;
            dgv.Columns.Add(column1);
            dgv.Columns.Add(column2);
            dgv.Columns.Add(column3);
            dgv.Rows.Add();
            dgv.Rows.Add();
            dgv.Rows.Add();

            panel.Controls.Add(dgv);
            ParentControl.Controls.Add(panel);
            ControlCount++;
            //TotalHeight = panel.Height + panel.Top;
        }
        public void AddTexttable2(string ControlName, Control ParentControl)
        {
            panel1.AutoScrollPosition = new Point(0, 0);
            UIPanel panel = new UIPanel();
            panel.Text = ControlCount + "#" + ControlName;
            panel.Name = ControlCount + "#" + ControlName;
            panel.Font = new Font("宋体", 9);
            //panel.Location = new Point(30, interval + TotalHeight);
            panel.Location = new Point(3, 96);
            panel.Size = new Size(994, 100);
            panel.Parent = ParentControl;
            panel.BringToFront();
            panel.Enter += uiPanel_Enter;
            panel.Leave += uiPanel_Leave;
            panel.ContextMenuStrip = contextMenuStrip1;

            DataGridView dgv = new DataGridView();
            dgv.Name = "dgv_" + ControlCount.ToString();
            dgv.Parent = panel;
            dgv.Location = new Point(3, 3);
            dgv.Size = new Size(panel.Width - 6, panel.Height - 6);
            dgv.RowHeadersVisible = false;
            dgv.BackgroundColor = Color.White;
            dgv.BorderStyle = BorderStyle.None;
            dgv.AllowUserToAddRows = false;
            dgv.AllowUserToDeleteRows = false;
            dgv.ReadOnly = true;
            dgv.ColumnHeadersVisible = false;
            dgv.RowTemplate.Height = 30;
            ParentControl.Controls.Add(dgv);
            DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn();
            DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
            DataGridViewTextBoxColumn column3 = new DataGridViewTextBoxColumn();
            column1.Width = dgv.Width / 3 - 1;
            column2.Width = dgv.Width / 3 - 1;
            column3.Width = dgv.Width / 3 - 1;
            dgv.Columns.Add(column1);
            dgv.Columns.Add(column2);
            dgv.Columns.Add(column3);
            dgv.Rows.Add();
            dgv.Rows.Add();
            dgv.Rows.Add();

            panel.Controls.Add(dgv);
            ParentControl.Controls.Add(panel);
            ControlCount++;
            //TotalHeight = panel.Height + panel.Top;
        }
        //public void AddRGtable(string ControlName, Control ParentControl)
        //{
        //    Label label = new Label();
        //    Label labe2 = new Label();
        //    Label labe3 = new Label();
        //    string[] c = ControlName.Split(new char[] { '#' });
        //    label.Name = ControlName;
        //    labe2.Name = ControlName;
        //    labe3.Name = ControlName;
        //    label.Text = c[8];
        //    labe2.Text = c[2];
        //    labe3.Text = c[9];
        //    label.AutoSize = false;
        //    labe2.AutoSize = false;
        //    labe3.AutoSize = false;
        //    label.TextAlign = ContentAlignment.MiddleLeft;
        //    labe2.TextAlign = ContentAlignment.MiddleCenter;
        //    labe3.TextAlign = ContentAlignment.MiddleRight;
        //    label.Width = 300;
        //    labe2.Width = 300;
        //    labe3.Width = 300;
        //    label.Location = new Point(30, interval + TotalHeight - 25);
        //    labe2.Location = new Point(380, interval + TotalHeight - 25);
        //    labe3.Location = new Point(730, interval + TotalHeight - 25);

        //    UIPanel panel = new UIPanel();
        //    panel.Text = ControlCount + "#" + ControlName;
        //    panel.Name = ControlCount + "#" + ControlName;
        //    panel.Font = new Font("宋体", 9);
        //    panel.Size = new Size(1000, 75);
        //    if (ParentControl == panel1)
        //    {
        //        panel1.AutoScrollPosition = new Point(0, 0);
        //        panel.Location = new Point(30, interval + TotalHeight);
        //        TotalHeight = panel.Height + panel.Top;

        //        ParentControl.Controls.Add(label);
        //        ParentControl.Controls.Add(labe2);
        //        ParentControl.Controls.Add(labe3);
        //    }
        //    else
        //    {
        //        panel.Location = new Point(0, 270);
        //    }

        //    panel.Parent = ParentControl;
        //    panel.BringToFront();
        //    panel.Enter += uiPanel_Enter;
        //    panel.Leave += uiPanel_Leave;
        //    panel.ContextMenuStrip = contextMenuStrip1;

        //    DataGridView dgv = new DataGridView();
        //    dgv.Name = "dgv_" + ControlCount.ToString();
        //    dgv.Parent = panel;
        //    dgv.Location = new Point(3, 3);
        //    dgv.Size = new Size(panel.Width - 6, panel.Height - 6);
        //    dgv.RowHeadersVisible = false;
        //    dgv.BackgroundColor = Color.White;
        //    dgv.BorderStyle = BorderStyle.None;
        //    dgv.AllowUserToAddRows = false;
        //    dgv.AllowUserToDeleteRows = false;
        //    dgv.DefaultCellStyle.Font = new Font("Arial", 6);
        //    dgv.ReadOnly = true;
        //    for (int i = 0; i < 32; i++)
        //    {
        //        DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
        //        if (i == 0)
        //        {
        //            column2.HeaderText = "Day";
        //        }
        //        else
        //        {
        //            column2.HeaderText = i.ToString();
        //        }
        //        column2.Width = dgv.Width / 32;
        //        dgv.Columns.Add(column2);
        //    }
        //    string[] b = ControlName.Split(new char[] { '#' });
        //    dgv.Rows.Add(b[4]);
        //    panel.Controls.Add(dgv);
        //    ParentControl.Controls.Add(panel);
        //    ControlCount++;
        //}
        //public void AddCharactertable(string ControlName, Control ParentControl)
        //{
        //    Label label = new Label();
        //    Label labe2 = new Label();
        //    Label labe3 = new Label();
        //    string[] c = ControlName.Split(new char[] { '#' });
        //    label.Text = c[8];
        //    labe2.Text = c[2];
        //    labe3.Text = c[9];
        //    label.AutoSize = false;
        //    labe2.AutoSize = false;
        //    labe3.AutoSize = false;
        //    label.TextAlign = ContentAlignment.MiddleLeft;
        //    labe2.TextAlign = ContentAlignment.MiddleCenter;
        //    labe3.TextAlign = ContentAlignment.MiddleRight;
        //    label.Width = 300;
        //    labe2.Width = 300;
        //    labe3.Width = 300;
        //    label.Location = new Point(30, interval + TotalHeight - 25);
        //    labe2.Location = new Point(380, interval + TotalHeight - 25);
        //    labe3.Location = new Point(730, interval + TotalHeight - 25);

        //    UIPanel panel = new UIPanel();
        //    panel.Text = ControlCount + "#" + ControlName;
        //    panel.Name = ControlCount + "#" + ControlName;
        //    panel.Font = new Font("宋体", 9);
        //    panel.Size = new Size(1000, 75);
        //    if (ParentControl == panel1)
        //    {
        //        panel1.AutoScrollPosition = new Point(0, 0);
        //        panel.Location = new Point(30, interval + TotalHeight);
        //        TotalHeight = panel.Height + panel.Top;
        //        ParentControl.Controls.Add(label);
        //        ParentControl.Controls.Add(labe2);
        //        ParentControl.Controls.Add(labe3);
        //    }
        //    else
        //    {
        //        panel.Location = new Point(0, 270);
        //    }
        //    panel.Parent = ParentControl;
        //    panel.BringToFront();
        //    panel.Enter += uiPanel_Enter;
        //    panel.Leave += uiPanel_Leave;
        //    panel.ContextMenuStrip = contextMenuStrip1;

        //    DataGridView dgv = new DataGridView();
        //    dgv.Name = "dgv_" + ControlCount.ToString();
        //    dgv.Parent = panel;
        //    dgv.Location = new Point(3, 3);
        //    dgv.Size = new Size(panel.Width - 6, panel.Height - 6);
        //    dgv.RowHeadersVisible = false;
        //    dgv.BackgroundColor = Color.White;
        //    dgv.BorderStyle = BorderStyle.None;
        //    dgv.AllowUserToAddRows = false;
        //    dgv.AllowUserToDeleteRows = false;
        //    dgv.DefaultCellStyle.Font = new Font("Arial", 6);
        //    dgv.ReadOnly = true;
        //    for (int i = 0; i < 32; i++)
        //    {
        //        DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
        //        if (i == 0)
        //        {
        //            column2.HeaderText = "Day";
        //        }
        //        else
        //        {
        //            column2.HeaderText = i.ToString();
        //        }
        //        column2.Width = dgv.Width / 32;
        //        dgv.Columns.Add(column2);
        //    }
        //    panel.Controls.Add(dgv);
        //    ParentControl.Controls.Add(panel);
        //    ControlCount++;
        //    string[] b = ControlName.Split(new char[] { '#' });
        //    if (b[3] == "1")
        //    {
        //        dgv.Rows.Add(b[4]);
        //    }
        //    else if (b[3] == "2")
        //    {
        //        dgv.Rows.Add(b[4]);
        //        dgv.Rows.Add(b[5]);
        //    }
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //panel点击事件
        private void uiPanel_Enter(object sender, EventArgs e)
        {
            Control clickedControl = sender as Control;
            if (clickedControl is UIPanel)
            {
                if (clickedControl.Parent == panel1)
                {
                    UIPanel uipanel = (UIPanel)sender;
                    uipanel.RectColor = Color.FromArgb(34, 45, 96);
                    uipanel.RectSize = 3;
                    //Console.WriteLine(uipanel.Name);
                    string[] b = uipanel.Name.Split(new char[] { '#' });
                    txtID1.Text = b[0];
                    cmbType1.Text = b[1];
                    txtName1.Text = b[2];
                    txtControlName1.Text = b[3];
                    cmbRowCount1.Text = b[4];
                    txtRow1.Text = b[5];
                    txtRow2.Text = b[6];
                    txtMax1.Text = b[7];
                    txtMin1.Text = b[8];
                    txtIndicator1.Text = b[9];
                    txtTarget1.Text = b[10];
                    EditControl1 = uipanel;
                }
                else
                {
                    Console.WriteLine("点击的是子窗体");
                }
            }
        }
        private void uiPanel_Leave(object sender, EventArgs e)
        {
            Control clickedControl = sender as Control;
            if (clickedControl is UIPanel)
            {
                UIPanel uipanel = (UIPanel)sender;
                uipanel.RectColor = Color.FromArgb(80, 160, 255);
                uipanel.RectSize = 1;
            }
        }
        //删除和保存事件
        private void btnDelete1_Click(object sender, EventArgs e)
        {
            if (txtID1.Text != "")
            {
                DialogResult dr = MessageBox.Show("确认删除?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (dr == DialogResult.OK)
                {
                    int heigh = 0;
                    int LineID = 0;
                    int JiShuQI = 0;
                    panel1.AutoScrollPosition = new Point(0, 0);
                    foreach (Control control in panel1.Controls)
                    {
                        string DeleteName = txtID1.Text + "#" + cmbType1.Text + "#" + txtName1.Text + "#" + txtControlName1.Text + "#" + cmbRowCount1.Text + "#" + txtRow1.Text + "#" + txtRow2.Text + "#" + txtMax1.Text + "#" + txtMin1.Text + "#" + txtIndicator1.Text + "#" + txtTarget1.Text;
                        if (control.Name == DeleteName)
                        {
                            LineID = Convert.ToInt32(txtID1.Text);
                            heigh = control.Height;
                            TotalHeight -= (heigh + interval);
                            panel1.Controls.Remove(control);
                            JiShuQI++;
                        }            
                    }
                    if (JiShuQI > 0)
                    {
                        foreach (Control control in panel1.Controls)
                        {
                            string[] b = control.Name.Split(new char[] { '#' });
                            if (Convert.ToInt32(b[0]) > LineID)
                            {
                                control.Top -= (heigh + interval);
                            }
                        }
                        txtID1.Text = "";
                        cmbType1.Text = "";
                        txtName1.Text = "";
                        txtControlName1.Text = "";
                        cmbRowCount1.Text = "";
                        txtRow1.Text = "";
                        txtRow2.Text = "";
                        txtMax1.Text = "";
                        txtMin1.Text = "";
                        txtIndicator1.Text = "";
                        txtTarget1.Text = "";
                        EditControl1 = null;
                    }
                }
            }
            else
            {
                MessageBox.Show("请选中一个已创建控件！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnSave1_Click(object sender, EventArgs e)
        {
            int a = panel1.Controls.Count;
            if (a > 0)
            {
                int FactoryID = Convert.ToInt32(cmbFactory1.SelectedValue);
                int DepartmentID = Convert.ToInt32(cmbDepartment1.SelectedValue);
                string Condition = "FactoryID=" + FactoryID + " and DepartmentID=" + DepartmentID;
                DataTable dt1 = SQL.ReturnDataTable3(SystemInfo.SQL, "Interface", Condition);
                if (dt1.Rows.Count > 0)
                {
                    SQL.Update(SystemInfo.SQL, "Interface", "Del_tag=1", Condition);
                }
                for (int i = 0; i < panel1.Controls.Count; i++)
                {
                    //Console.WriteLine(panel1.Controls[i].Name);
                    if (panel1.Controls[i].Name != null)
                    {
                        string[] N = panel1.Controls[i].Name.Split(new char[] { '#' });
                        if (N.Length == 11)
                        {
                            SaveLayout(FactoryID, DepartmentID, panel1.Controls[i].Name);
                            if (N[2] == "折线图")
                            {
                                SaveLayout(FactoryID, DepartmentID, panel1.Controls[i].Controls[1].Name);
                            }
                            else if (N[2] == "红绿表格")
                            {
                                if (panel1.Controls[i].Controls.Count > 4)
                                {
                                    SaveLayout(FactoryID, DepartmentID, panel1.Controls[i].Controls[4].Name);
                                }
                            }
                        }
                    }
                }
            }
        }
        private int Level = 0;
        private void SaveLayout(int FactoryID, int DepartmentID, string Name1)
        {
            
            string[] N = Name1.Split(new char[] { '#' });
            string ControlOrder = N[0];
            string ControlName = N[3];
            string KPItype = N[1];
            string ControlType = N[2];
            string RowType = N[4];
            string RowTitle1 = N[5];
            string RowTitle2 = N[6];
            string MaxTarget = N[7];
            string MinTarget = N[8];
            string Indicator = N[9];
            string Target = N[10];
            //获取部门ID
            int depID = (int)cmbDepartment1.SelectedValue;
            string query = $@"WITH DepartmentLevels AS (
    -- 基础部分：ParentDepartmentID 为 NULL 的部门为 Level 4
    SELECT
        ID,
        DepartmentName,
        FactoryID,
        ParentDepartmentID,
        4 AS DepartmentLevel
    FROM Departments
    WHERE ParentDepartmentID = 0 and Del_tag = 0

    UNION ALL

    -- 递归部分：子部门的层级为父部门层级减 1
    SELECT
        d.ID,
        d.DepartmentName,
        d.FactoryID,
        d.ParentDepartmentID,
        dl.DepartmentLevel - 1 AS DepartmentLevel
    FROM Departments d
    INNER JOIN DepartmentLevels dl ON d.ParentDepartmentID = dl.ID
    WHERE dl.DepartmentLevel > 1 and Del_tag  = 0
)
SELECT
    ID,
    DepartmentName,
    FactoryID,
    ParentDepartmentID,
    DepartmentLevel
FROM DepartmentLevels
where ID = {depID}
ORDER BY DepartmentLevel DESC, DepartmentName
OPTION (MAXRECURSION 10);  -- 防止递归过深";
            DataTable dtLV = SQL.ReturnDataTable(SystemInfo.SQL,query);
            if (dtLV.Rows.Count > 0)
            {
                Level = (int)dtLV.Rows[0]["DepartmentLevel"];
            }
            else
            {
                MessageBox.Show("Failed to get the department level correctly","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            int Del_tag = 0;
            string Items = "FactoryID,DepartmentID,ControlOrder,ControlName,KPItype,ControlType,RowType,RowTitle1,RowTitle2,MaxTarget,MinTarget,Indicator,[Target/Limit],Level,Del_tag";
            string Values = $"{FactoryID},{DepartmentID},'{ControlOrder}','{ControlName}','{KPItype}','{ControlType}','{RowType}','{RowTitle1}','{RowTitle2}','{MaxTarget}','{MinTarget}','{Indicator}','{Target}',{Level},{Del_tag}";
            if (SQL.Insert(SystemInfo.SQL, "Interface", Items, Values) > 0)
            {
                Sunny.UI.UIMessageTip.Show("成功！", Sunny.UI.TipStyle.Green);
            }
        }
        //移动事件
        private void 移动控件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 使用ContextMenuStrip的SourceControl属性获取触发上下文菜单的Panel
            UIPanel sourcePanel = contextMenuStrip1.SourceControl as UIPanel;
            if (sourcePanel != null && sourcePanel.Parent == panel1)
            {
                control1 = sourcePanel;
                string[] b = sourcePanel.Name.Split(new char[] { '#' });
                移动控件ToolStripMenuItem.Text = "移动控件(ID:" + b[0] + ")";
            }
        }
        private void 被移动控件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 使用ContextMenuStrip的SourceControl属性获取触发上下文菜单的Panel
            UIPanel sourcePanel = contextMenuStrip1.SourceControl as UIPanel;
            if (sourcePanel != null && sourcePanel.Parent == panel1)
            {
                control2 = sourcePanel;
                string[] b = sourcePanel.Name.Split(new char[] { '#' });
                被移动控件ToolStripMenuItem.Text = "被移动控件(ID:" + b[0] + ")";
            }
        }
        private void MoveControl1_Click(object sender, EventArgs e)
        {
            if (control1 != null && control2 != null)
            {
                string[] a = control1.Name.Split(new char[] { '#' });
                string[] b = control2.Name.Split(new char[] { '#' });
                string name1 = string.Join("#", a, 1, a.Length - 1);
                string name2 = string.Join("#", b, 1, b.Length - 1);
                int ID1 = Convert.ToInt32(a[0]);
                int ID2 = Convert.ToInt32(b[0]);
                if (ID1 > ID2)
                {
                    control1.Top = control2.Top;
                    control2.Top = control1.Top + control1.Height + interval;
                }
                else
                {
                    control2.Top = control1.Top;
                    control1.Top = control2.Top + control2.Height + interval;
                }

                移动控件ToolStripMenuItem.Text = "移动控件";
                被移动控件ToolStripMenuItem.Text = "被移动控件";
                control1.Name = ID2 + "#" + name1;
                control2.Name = ID1 + "#" + name2;
                if (a[2] == "折线图")
                {
                    foreach (Control control in control1.Controls)
                    {
                        string[] c = control.Name.Split(new char[] { '#' });
                        string name3 = string.Join("#", c, 1, c.Length - 1);
                        if (c.Length > 2)
                        {
                            control.Name = ID2 + "#" + name3;
                        }
                    }
                }
                control1 = null;
                control2 = null;
            }
        }
        //修改属性
        private void btnEdit1_Click(object sender, EventArgs e)
        {
            if (btnEdit1.Text == "修改属性")
            {
                panel2.Enabled = true;
                btnCancel1.Visible = true;
                btnEdit1.Text = "保存";
                btnEdit1.Symbol = 61639;
            }
            else
            {
                if (EditControl1 != null)
                {
                    EditControl1.Name = txtID1.Text + "#" + cmbType1.Text + "#" + txtName1.Text + "#" + txtControlName1.Text + "#" + cmbRowCount1.Text + "#" + txtRow1.Text + "#" + txtRow2.Text + "#" + txtMax1.Text + "#" + txtMin1.Text + "#" + txtIndicator1.Text + "#" + txtTarget1.Text;
                    panel2.Enabled = false;
                    btnCancel1.Visible = false;
                    btnEdit1.Text = "修改属性";
                    btnEdit1.Symbol = 560260;
                    Sunny.UI.UIMessageTip.Show("属性修改成功，记得点击保存设置。", Sunny.UI.TipStyle.Green);     
                }
            }
        }
        private void btnCancel1_Click(object sender, EventArgs e)
        {
            if (btnCancel1.Text == "取消")
            {
                panel2.Enabled = false;
                btnCancel1.Visible = false;
                btnEdit1.Text = "修改属性";
                btnEdit1.Symbol = 560260;
            }
        }
        private void txtMax1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许退格键  
            if (e.KeyChar == (char)Keys.Back)
            {
                return; // 不做任何处理，允许退格键操作  
            }
            // 允许输入的字符包括数字0-9和点号  
            char ch = e.KeyChar;
            if (!Char.IsDigit(ch) && ch != '.')
            {
                // 如果不是数字也不是点号，则阻止按键事件  
                e.Handled = true;
            }
            // 可选：如果需要限制小数点只能出现一次  
            // 获取TextBox的当前文本  
            string text = ((TextBox)sender).Text;
            // 检查是否已存在小数点，并且用户没有尝试删除它  
            if (ch == '.' && text.Contains(".") && !e.KeyChar.Equals(Keys.Back))
            {
                e.Handled = true;
            }

        }
        private void txtMin1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许退格键  
            if (e.KeyChar == (char)Keys.Back)
            {
                return; // 不做任何处理，允许退格键操作  
            }
            // 允许输入的字符包括数字0-9和点号  
            char ch = e.KeyChar;
            if (!Char.IsDigit(ch) && ch != '.')
            {
                // 如果不是数字也不是点号，则阻止按键事件  
                e.Handled = true;
            }
            // 可选：如果需要限制小数点只能出现一次  
            // 获取TextBox的当前文本  
            string text = ((TextBox)sender).Text;
            // 检查是否已存在小数点，并且用户没有尝试删除它  
            if (ch == '.' && text.Contains(".") && !e.KeyChar.Equals(Keys.Back))
            {
                e.Handled = true;
            }

        }
        private void txtName1_TextChanged(object sender, EventArgs e)
        {
            if (txtName1.Text == "红绿表格")
            {
                cmbRowCount1.Enabled = false;
                txtMax1.ReadOnly = true;
                txtMin1.ReadOnly = true;
            }
            else if (txtName1.Text == "文字表格")
            {
                cmbRowCount1.Enabled = true;
                txtMax1.ReadOnly = false;
                txtMin1.ReadOnly = false;
            }
            else if (txtName1.Text == "文本表格")
            {
                cmbRowCount1.Enabled = false;
                txtMax1.ReadOnly = true;
                txtMin1.ReadOnly = true;
            }
            else if (txtName1.Text == "折线图")
            {
                cmbRowCount1.Enabled = false;
                txtMax1.ReadOnly = false;
                txtMin1.ReadOnly = false;
            }
        }
        private void cmbRowCount1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbRowCount1.Text == "1")
            {
                txtRow1.ReadOnly = false;
                txtRow2.ReadOnly = true;
            }
            else if (cmbRowCount1.Text == "2")
            {
                txtRow1.ReadOnly = false;
                txtRow2.ReadOnly = false;
            }
            else
            {
                txtRow1.ReadOnly = true;
                txtRow2.ReadOnly = true;
            }
        }
    }
}